﻿using System.Collections.Generic;

namespace SocketCore
{
    public class NetworkHandlerChain
    {
        private List<INetworkHandler> filters;

        public NetworkHandlerChain()
        {
            this.filters = new List<INetworkHandler>();
        }

        public NetworkHandlerChain(INetworkHandler handler)
        {
            this.filters = new List<INetworkHandler>();
            handler.NextNetworkHandler = null;
            this.filters.Add(handler);
        }

        #region methods

        public void AddFilter(int index, INetworkHandler filter)
        {
            if (index > 0)
            {
                INetworkHandler formerFilter = this.filters[index - 1];
                formerFilter.NextNetworkHandler = filter;
            }
            if (index < this.filters.Count)
            {
                filter.NextNetworkHandler = this.filters[index];
            }
            this.filters.Insert(index, filter);
        }

        public void AppendFilter(INetworkHandler filter)
        {
            this.AddFilter(this.filters.Count, filter);
        }

        public INetworkHandler FirstHandler()
        {
            if (this.filters.Count > 0)
            {
                return this.filters[0];
            }
            return null;
        }

        #endregion
    }
}
